"""
@Project ：PythonInterfaceFrame 
@File    ：ReadDataUtil.py
@IDE     ：PyCharm 
@Author  ：ceiling
@Date    ：2025/4/25 19:59 
"""
import openpyxl
from pathlib import Path
import json
import yaml


class ReadDataUtil:

    @classmethod
    def load_excel_data(cls, excel_path, sheet_name=None, *fields):
        """
        读取 Excel 文件并转换为适合 pytest 参数化的列表元组格式 [(...), (...)]

        :param excel_path: Excel 文件路径
        :param sheet_name: 指定 sheet 名，默认第一个
        :param fields: 你希望提取的字段名（标题行的字段）
        :return: list[tuple]
        """
        excel_file = Path(excel_path)
        if not excel_file.exists():
            raise FileNotFoundError(f"Excel 文件不存在: {excel_path}")

        wb = openpyxl.load_workbook(excel_file)
        sheet = wb[sheet_name] if sheet_name else wb.active

        # 获取表头
        headers = [cell.value for cell in next(sheet.iter_rows(min_row=1, max_row=1))]

        # 字段索引列表
        if not fields:
            # 如果不传 fields，默认用全部字段
            fields = headers
        field_indexes = [headers.index(f) for f in fields]

        result = []
        for row in sheet.iter_rows(min_row=2, values_only=True):
            row_data = tuple(row[i] for i in field_indexes)
            result.append(row_data)
        return result

    @classmethod
    def load_json_data(cls, filepath):
        """
        :param filepath: json文件路径
        :return: 返回list集合
        """
        # 创建一个空列表 用于存储数据
        list_data = []
        # 调用with open 方法打开本地文件
        # with open 方法不用手动去关闭流
        with open(filepath, "r", encoding="utf8") as f:
            data = json.load(f)  # 调用load方法加载本地的json文件
            for json_data in data:
                t = tuple(json_data.values())  # 取得json文件数据 将其转化为元组
                list_data.append(t)  # 将从json文件当中取得的值重新添加到空列表当中
            return list_data

    @classmethod
    def load_yaml_data(cls, yaml_path, *fields):
        """
        读取 YAML 文件并转换为 pytest 参数化格式：[(...), (...)]

        :param yaml_path: YAML 文件路径
        :param fields: 想要提取的字段名（顺序决定顺序）
        :return: list[tuple]
        """
        yaml_file = Path(yaml_path)
        if not yaml_file.exists():
            raise FileNotFoundError(f"YAML 文件不存在: {yaml_path}")

        with open(yaml_file, encoding='utf-8') as f:
            data = yaml.safe_load(f)

        result = []
        # 处理列表结构
        if isinstance(data, list):
            for item in data:
                result.append(tuple(item[field] for field in fields))
        # 处理字典结构
        elif isinstance(data, dict):
            for key, item in data.items():
                result.append(tuple(item[field] for field in fields))
        else:
            raise TypeError("YAML 数据必须是 list 或 dict 格式")

        return result
